<?php
namespace app\common\model\logic;

use think\Model;

class CarModel extends Model {

    private $request;
    protected $name = 'car'; //定义栏目表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = true;
    //类型自动转换
    protected $type = [
        'car_seat'=>'integer',
        'car_buy_price'=>'float',
        'sort'=>'integer'
    ];
    //初始化
    function __construct($data = [])
    {
        parent::__construct($data);
        $this->request=\think\Request::instance();
    }
    public function getCarStatusTextAttr($value, $data)
    {
        $arr=['0'=>'可用','1'=>'出车','2'=>'维修','3'=>'保养'];
        return $arr[$data['car_status']];
    }
    public function getCarDisableTextAttr($value, $data)
    {
        $arr=['0'=>'停用','1'=>'正常使用'];
        return $arr[$data['car_disable']];
    }


    /**
     * 获取检索条件
     * @param $query
     */
    public function getExtendMap($query){
        return [];
    }
    /**
     * 获取多条记录
     * @param $map
     * @param string $type
     * @param array $params
     * 带分页条：paginate:['pagesize'=>12,'simple'=>false]
     * 普通分页查询:page:['page'=>1,'pagesize'=>12]
     * 普通查询: limit: "1,20"
     * @return false|null|\PDOStatement|string|\think\Collection|\think\Paginator
     * @throws \Exception
     */
    public function getlist($map,$type='paginate',$params=['pagesize'=>12,'simple'=>false]){
        $list=null;
        $dao = $this->field(true)->where($map)->order('sort desc');
        if($type=='paginate'){
            $list = $dao->paginate($params['pagesize'], $params['simple'], ['query' => $this->request->query()]);
        }
        if($type=='page'){
            $list = $dao->page($params['page'],$params['pagesize'])->select();
        }
        if($type=='limit'){
            $list = $dao->limit($params)->select();
        }
        return $list;
    }

    //读取单条数据
    public function read($aid){
        try{
            $info = $this->get($aid)->toArray();
            return $info;
        } catch (\Exception $e){
            exception($e->getMessage(),40001);
        }
    }
    //添加数据
    public function add($data){
        try{
            $this->isUpdate(false)->allowField(true)->save($data);
            return true;
        }catch (\Exception $e){
            exception($e->getMessage(),40001);
        }
    }
    //修改数据
    public function edit($data){
        try{

            $this->isUpdate(true)->allowField(true)->save($data);
            return true;
        } catch (\Exception $e){
            exception($e->getMessage(),40001);
        }
    }
    //删除数据
    public function del($aid){
        try{
            $this->destroy($aid);
            return true;
        } catch (\Exception $e){
            exception($e->getMessage(),40001);
        }
    }
}